package com.start.common.registers;

import com.start.common.tools.HQScanPackage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 注册器工厂
 */
@Slf4j
@Component
public class StartRegisterFactory implements HQScanPackage.HQScanPackageListener {

    @Autowired(required = false)
    private Map<String, StartBaseRegister> registerMap;
    @Autowired(required = false)
    private Map<String, BaseScanPackageRegister> packageRegisterMap;

    public void register() {
        if (packageRegisterMap == null || packageRegisterMap.size() < 1) {
            log.warn("未找到包注册器，系统自动放弃自动注册功能");
            return;
        }
        if (registerMap == null || registerMap.size() < 1) {
            log.warn("未找到需要注册的包，系统自动放弃自动注册功能");
            return;
        }
        registerMap.forEach((s, startBaseRegister) -> startBaseRegister.init());

        List<String> basePackages = new ArrayList<>();
        for (Map.Entry<String, BaseScanPackageRegister> entry : packageRegisterMap.entrySet()) {
            com.start.common.registers.BaseScanPackageRegister value = entry.getValue();
            String[] pa = entry.getValue().getPackages();
            if (pa == null || pa.length < 1) continue;
            List<String> collect = Arrays.stream(pa).filter(p -> !StringUtils.isEmpty(p)).collect(Collectors.toList());
            if (collect.size() < 1) continue;
            basePackages.addAll(collect);
        }
        if (basePackages.size() < 1) return;
        basePackages = basePackages.stream().distinct().collect(Collectors.toList());
        HQScanPackage scanPackage = new HQScanPackage();
        scanPackage.addPackage(basePackages);
        scanPackage.setListener(this);
        scanPackage.scan();
        registerMap.forEach((s, startBaseRegister) -> startBaseRegister.destroy());
    }

    @Override
    public void onScanClass(Class<?> clazz) {
        for (Map.Entry<String, StartBaseRegister> entry : registerMap.entrySet()) {
            StartBaseRegister register =entry.getValue();
            if (!register.getInitState()) continue;
            if (register.getAnnotationsClass() == null) continue;
            Annotation annotation = AnnotationUtils.findAnnotation(clazz,register.getAnnotationsClass());
            if (annotation == null) continue;
            try {
                register.register(clazz);
            } catch (Exception e) {
                log.error("注册器异常：" + register.getClass());
                e.printStackTrace();
            }
        }
    }
}
